﻿using System;
using System.Data.SqlClient;
using Devv.Core.UniDataTier;
using Yglu.BusinessLayer.Entities;

namespace Yglu.BusinessLayer
{
	public partial class DataAccess
	{
		#region Get

		public static SqlDataReader Order_Get(Int32 id)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@OrderId", id);

			return (SqlDataReader)db.ExecuteReader("upOrder_Get");
		}

		public static SqlDataReader Order_Get(Period period)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@DateFrom", period.DateFrom);
			db.AddParameter("@DateTo", period.DateTo);

			return (SqlDataReader)db.ExecuteReader("upOrder_Get");
		}

		public static SqlDataReader Order_Get(Store store, Period period)
		{
			DataHandler db = new DataHandler();

			if (store != null && store.Id > 0)
			{
				db.AddParameter("@StoreId", store.Id);
			}
            
			db.AddParameter("@DateFrom", period.DateFrom);
			db.AddParameter("@DateTo", period.DateTo);

			return (SqlDataReader)db.ExecuteReader("upOrder_Get");
		}

		#endregion

		#region Insert and update

		public static void Order_Upsert(Order order)
		{
			using (DataHandler db = new DataHandler())
			{
				db.AddParameter("@TerminalId", order.Terminal.Id);
				db.AddParameter("@UserId", order.User.Id);
				db.AddParameter("@PaymentType", order.PaymentType);
				db.AddParameter("@Customer", order.Customer);
				db.AddParameter("@TotalPrice", order.TotalPrice);
				db.AddParameter("@Discount", order.Discount);
				db.AddParameter("@DateOrdered", order.DateOrdered);
				db.AddParameter("@DatePaid", order.DatePaid);
				db.AddParameter("@Active", order.Active);
				db.AddParameter("@ComboIds", order.Combos.GetIds());

				PromotionCollection promotions = new PromotionCollection();

				if (order.PromotionApplied != null && order.PromotionApplied.Id > 0)
				{
					promotions.Add(order.PromotionApplied);
				}

				foreach (Combo c in order.Combos)
				{
					if (c.PromotionApplied != null && c.PromotionApplied.Id > 0)
					{
						promotions.Add(c.PromotionApplied);
					}
				}

				if (promotions.Count > 0)
				{
					db.AddParameter("@PromotionIds", promotions.GetIds());
				}

				if (order.Id > 0)
				{
					db.AddParameter("@OrderId", order.Id);
					db.ExecuteScalar("upOrder_Update");
				}
				else
				{
					order.Id = Convert.ToInt32(db.ExecuteScalar("upOrder_Insert"));
				}
			}
		}

		#endregion
	}
}
